import wx
import os
import gui


class ConvertFrame(gui.MainWindow):
    def __init__(self, parent):
        gui.MainWindow.__init__(self, parent)

    def convert_func(self, event):
        self.errfiles = set()
        for l in self.text.GetValue().splitlines():
            try:
                handle_single_xls(l)
            except Exception as e:
                print(e)
                self.errfiles.update([l])

        if self.errfiles:
            infos = '完成！以下文件处理出现问题：\n\n' + '\n'.join(self.errfiles)
        else:
            infos = f'完成 {len(self.text.GetValue().splitlines())} 个文件的转换'

        wx.MessageBox(infos, '结果')

    def clear_func(self, event):
        self.text.SetValue('')


def handle_single_xls(s):
    import pandas as pd
    df = pd.read_excel(s)
    df = df.melt(id_vars='地区', var_name='year', value_name='low')
    df.rename(index=str, columns={'地区': 'province'}, inplace=True)
    df['year'] = pd.to_numeric(df['year'].str.replace('年', ''))
    df.to_excel('-convert'.join(os.path.splitext(s)), index=False)


app = wx.App(False)
frame = ConvertFrame(None)
frame.Show(True)
app.MainLoop()
